const prisma = require('../utils/prisma');
const { hashPassword, comparePassword } = require('../utils/password');
const { generateToken } = require('../utils/jwt');
const { success, error } = require('../utils/response');
const wechatService = require('../services/wechatService');

/**
 * 用户登录
 * @route POST /api/auth/login
 */
const login = async (req, res) => {
  try {
    const { username, password, loginType } = req.body;
    
    // 微信登录
    if (loginType === 'wechat') {
      const { code, userInfo } = req.body;
      
      if (!code) {
        return error(res, 'WeChat code is required', 400);
      }
      
      // 获取微信 OpenID
      const { openid } = await wechatService.getOpenId(code);
      
      // 查找或创建用户
      let user = await prisma.user.findUnique({
        where: { openid }
      });
      
      if (!user) {
        // 创建新用户
        user = await prisma.user.create({
          data: {
            name: userInfo?.nickName || '微信用户',
            avatar: userInfo?.avatarUrl,
            openid
          }
        });
      }
      
      // 生成 token
      const token = generateToken({
        id: user.id,
        role: user.role
      });
      
      return success(res, {
        token,
        user: {
          id: user.id,
          name: user.name,
          avatar: user.avatar,
          role: user.role
        }
      });
    }
    
    // 账号密码登录
    if (!username || !password) {
      return error(res, 'Username and password are required', 400);
    }
    
    // 查找用户
    const user = await prisma.user.findFirst({
      where: {
        OR: [
          { phone: username },
          { name: username }
        ]
      }
    });
    
    if (!user || !user.password) {
      return error(res, 'Invalid credentials', 401);
    }
    
    // 验证密码
    const isPasswordValid = await comparePassword(password, user.password);
    
    if (!isPasswordValid) {
      return error(res, 'Invalid credentials', 401);
    }
    
    // 生成 token
    const token = generateToken({
      id: user.id,
      role: user.role
    });
    
    return success(res, {
      token,
      user: {
        id: user.id,
        name: user.name,
        phone: user.phone,
        avatar: user.avatar,
        role: user.role
      }
    });
  } catch (err) {
    console.error('Login error:', err);
    return error(res, 'Login failed', 500);
  }
};

/**
 * 用户注册
 * @route POST /api/auth/register
 */
const register = async (req, res) => {
  try {
    const { name, phone, password } = req.body;
    
    if (!name || !phone || !password) {
      return error(res, 'Name, phone and password are required', 400);
    }
    
    // 检查手机号是否已存在
    const existingUser = await prisma.user.findUnique({
      where: { phone }
    });
    
    if (existingUser) {
      return error(res, 'Phone number already registered', 409);
    }
    
    // 哈希密码
    const hashedPassword = await hashPassword(password);
    
    // 创建用户
    const user = await prisma.user.create({
      data: {
        name,
        phone,
        password: hashedPassword
      }
    });
    
    // 生成 token
    const token = generateToken({
      id: user.id,
      role: user.role
    });
    
    return success(res, {
      token,
      user: {
        id: user.id,
        name: user.name,
        phone: user.phone,
        role: user.role
      }
    }, 'Registration successful', 201);
  } catch (err) {
    console.error('Registration error:', err);
    return error(res, 'Registration failed', 500);
  }
};

/**
 * 获取当前用户信息
 * @route GET /api/auth/me
 */
const getMe = async (req, res) => {
  try {
    const userId = req.user.id;
    
    const user = await prisma.user.findUnique({
      where: { id: userId },
      select: {
        id: true,
        name: true,
        phone: true,
        avatar: true,
        role: true,
        createdAt: true
      }
    });
    
    if (!user) {
      return error(res, 'User not found', 404);
    }
    
    return success(res, user);
  } catch (err) {
    console.error('Get user error:', err);
    return error(res, 'Failed to get user information', 500);
  }
};

module.exports = {
  login,
  register,
  getMe
};
